package com.lemonfish.service.impl;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.diboot.core.util.BeanUtils;
import com.lemonfish.mapper.GoodsCateMapper;
import com.lemonfish.pojo.entity.GoodsCate;
import com.lemonfish.pojo.entity.GoodsParam;
import com.lemonfish.pojo.vo.GoodsCateVO;
import com.lemonfish.service.GoodsCateService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.stream.Collectors;

/**
 * 商品分类相关Service实现
 *
 * @author Lemonfish
 * @version 1.begin
 * @date 2020-03-07
 * Copyright © Chao Zhang
 */
@Service
@Slf4j
public class GoodsCateServiceImpl extends BaseCustomServiceImpl<GoodsCateMapper, GoodsCate> implements GoodsCateService {
    @Autowired
    GoodsCateMapper goodsCateMapper;

    @Override
    public IPage<GoodsCate> showList(long curPage, long size) {
        IPage<GoodsCate> page = goodsCateMapper.selectPage(new Page<GoodsCate>(curPage, size), null);
        List<GoodsCate> goodsCates = goodsCateMapper.selectList(null);
        List<GoodsCate> treeList = BeanUtils.buildTree(goodsCates);

        long total = treeList.size();
        int begin = (int) ((curPage - 1) * size);
        int end;
        // 第一页情况比较特殊，需要另外处理
        // 如果total <= size那么  end 则为total 否则为size
        if (begin == 0) {
            end = (int) (Math.min(total, size));
        } else {
            // 这里取模才能处理成功，因为如果total为7 ，size=5，那么第二页的时候肯定是5，7，因此需要取模计算
            end = (int) (total % size == 0 ? curPage * size : begin + total % size);
        }

        page.setRecords(total >= size ? treeList.subList(begin, end) : treeList);
        page.setTotal(total);

        return page;
    }

    @Override
    public List<GoodsParam> getParamsList(long cateId, String type) {
        GoodsCateVO vo = this.getViewObject(cateId, GoodsCateVO.class);

        List<GoodsParam> goodsparamList = vo.getGoodsparamList();
        return "static".equals(type) ? BeanUtils.buildTree(goodsparamList.stream().filter(item -> !item.getParamType()).collect(Collectors.toList()))
                : BeanUtils.buildTree(goodsparamList.stream().filter(GoodsParam::getParamType).collect(Collectors.toList()));
    }
}
